package grape.wx.rest.mp.basic.mvc;

import grape.common.exception.ExceptionCode;
import grape.common.exception.ExceptionTools;
import grape.common.exception.runtime.InvalidParamsException;
import grape.common.rest.advice.DisableGRB;
import grape.common.rest.advice.DisableGRM;
import grape.common.rest.mvc.SuperController;
import grape.wx.service.mp.MpProperties;
import grape.wx.service.mp.user.api.IMpUserService;
import grape.wx.service.mp.user.po.MpUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import me.chanjar.weixin.mp.util.WxMpConfigStorageHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * Created by yangwei
 * Created at 2020/7/20 20:48
 */
@Slf4j
@RestController
@RequestMapping("/wx/mp/oauth2/{appId}")
public class MpOAuth2InnerController extends SuperController {

    @Autowired
    private WxMpService wxMpService;
    @Autowired
    private IMpUserService iMpUserService;
    @Autowired
    private MpProperties mpProperties;

    @DisableGRM
    @DisableGRB
    @ResponseStatus(HttpStatus.OK)
    @GetMapping("/oauth2getUserInfo")
    public MpUser oauth2getUserInfo(@PathVariable String appId, String code) {
        wxMpService.switchover(appId);
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken = null;
        try {
            wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
        } catch (WxErrorException e) {
            log.error(e.getMessage(),e);
            throw ExceptionTools.invalidParamsRE("网页授权接口调用凭证失败，请检查code是否正确");
        }
        boolean valid = wxMpService.oauth2validateAccessToken(wxMpOAuth2AccessToken);
        if (!valid) {
            // 刷新token失败，应该重新引导用户授权
            try {
                wxMpOAuth2AccessToken = wxMpService.oauth2refreshAccessToken(wxMpOAuth2AccessToken.getRefreshToken());
            } catch (WxErrorException e) {
                log.error(e.getMessage(),e);
                throw new InvalidParamsException(ExceptionCode.wx_mp_re_oauth2, ExceptionCode.wx_mp_re_oauth2.getMsg());
            }
        }
        MpProperties.MpConfig mpConfig = mpProperties.abtainConfigByAppCodeOrAppId(WxMpConfigStorageHolder.get());
        MpUser byOpenidAndAppCode = iMpUserService.getByOpenidAndAppCode(wxMpOAuth2AccessToken.getOpenId(), mpConfig.getAppCode());
        try {
            WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);
            if (byOpenidAndAppCode == null) {
                iMpUserService.insert(wxMpUser, mpConfig, MpUser.DictHowFrom.wx_mp_user_how_from_oauth2);
            }else {
                MpUser mpUser = new MpUser();
                mpUser.setId(byOpenidAndAppCode.getId());
                iMpUserService.updateById(wxMpUser, mpConfig,mpUser );
            }
        } catch (WxErrorException e) {
            if (byOpenidAndAppCode == null) {
                throw ExceptionTools.invalidParamsRE("获取用户信息失败");
            }
        }

        if (byOpenidAndAppCode == null) {
            return null;
        }
        return iMpUserService.getById(byOpenidAndAppCode.getId());
    }
}
